<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 表单 - 整个页面结构的第一行 -->
        <el-form label-width="80px">
          <el-row>
            <!-- 关键字 -->
            <el-col :span="5">
              <div class="grid-content bg-purple">
                <el-form-item label="关键字">
                  <el-input v-model="keyword" placeholder="根据文章标题搜索" style="width: 192px">
                  </el-input>
                </el-form-item>
              </div>
            </el-col>
            <!-- 状态 -->
            <el-col :span="6">
              <div class="grid-content bg-purple-light">
                <el-form-item label="状态">
                  <el-select v-model="isState" placeholder="请选择">
                    <el-option
                      v-for="item in allState"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
            <!-- 按钮 -清除 和 搜索 -->
            <el-col :span="11">
              <div class="grid-content bg-purple">
                <el-button @click="clearAllData">清除</el-button>
                <el-button @click="searchFind" type="primary">搜索</el-button>
              </div>
            </el-col>
            <!-- 添加 -新增技巧按钮 -->
            <el-col :span="1">
              <div class="grid-content bg-purple">
                <el-button
                  @click="addArticleShowDialog"
                  type="success"
                  size="small"
                  icon="el-icon-edit"
                  style="font-size: 14px"
                >
                  新增技巧
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>

        <!-- 提示 -->
        <el-alert :title="`数据一共 ${total} 条`" type="info" :closable="false" show-icon>
        </el-alert>

        <!-- 表格 -->
        <el-table
          size="medium"
          :data="tableData"
          :header-cell-style="{
            borderBottom: '2px solid #e8e8e8',
            background: '#fafafa'
          }"
          style="width: 100%"
          :row-style="{ height: '72px' }"
        >
          <!-- 序号 -->
          <el-table-column type="index" :index="indexFn" label="序号" width="60"> </el-table-column>
          <!-- 文章标题 -->
          <el-table-column label="文章标题" width="400">
            <template #default="{ row }">
              {{ row.title }}
              <!-- 字体图标 -->
              <span
                class="el-icon-film"
                @click="showMaskLayer(row.videoURL)"
                v-if="row.videoURL != null"
              ></span>
            </template>
          </el-table-column>
          <!-- 阅读数 -->
          <el-table-column prop="visits" label="阅读数"> </el-table-column>
          <!-- 录入人 -->
          <el-table-column prop="username" label="录入人"> </el-table-column>
          <!-- 录入时间 -->
          <el-table-column prop="createTime" label="录入时间" width="180">
            <template #default="{ row }">
              {{ timeFn(row.addDate) }}
            </template>
          </el-table-column>
          <!-- 状态 -->
          <el-table-column prop="state" label="状态" width="80" :formatter="stateTypeFn">
          </el-table-column>
          <!-- 操作 -->
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button type="text" @click="openPreviewDialog(row)">预览</el-button>
              <el-button type="text" @click="disable(row)">{{
                row.state === 1 ? '禁用' : '启用'
              }}</el-button>
              <el-button type="text" :disabled="row.state === 1" @click="updateArticle(row)"
                >修改</el-button
              >
              <el-button type="text" :disabled="row.state === 1" @click="deleteArticle(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="hmmm_wrapper">
          <el-pagination
            background
            :current-page="page"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pagesize"
            layout=" prev,pager,next,sizes,jumper"
            :total="total"
            @size-change="pageDataAmount"
            @current-change="goToPage"
          >
          </el-pagination>
        </div>
      </el-card>
      <!-- 新增文章dialog 对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="addShowDialog" @close="cancel">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <!-- 文章标题 -->
          <el-form-item label="文章标题" prop="ruleFormTitle">
            <el-input v-model="ruleForm.ruleFormTitle" placeholder="请输入文章标题"></el-input>
          </el-form-item>
          <!-- 富文本编辑器 -->
          <el-form-item label="文章内容" prop="ruleFormText">
            <div class="fuwenben">
              <quillEditor
                style="height: 180px"
                v-model="ruleForm.ruleFormText"
                :options="editorOption"
              ></quillEditor>
            </div>
          </el-form-item>
          <!-- 视频地址 -->
          <el-form-item label="视频地址" prop="ruleFormAddress">
            <el-input v-model="ruleForm.ruleFormAddress" placeholder="请输入视频地址"></el-input>
          </el-form-item>

          <!-- 按钮 -->
          <div class="hmmm_wrapper" style="margin: 0">
            <el-button @click="cancel">取消</el-button>
            <el-button @click="Confirmation" type="primary">确认</el-button>
          </div>
        </el-form>
      </el-dialog>

      <!-- 预览文章dialog 对话框 -->
      <el-dialog title="预览文章" :visible.sync="previewShowDialog">
        <div class="title">
          <h2 style="margin: 0; padding: 0">{{ previewData.title }}</h2>
          <div>
            <span>{{ timeFn(previewData.addDate) }}</span>
            <span>{{ previewData.username }}</span>
            <span class="el-icon-view"></span>
            <span>{{ previewData.visits }}</span>
          </div>
        </div>
        <div class="content" v-html="previewData.articleBody"></div>
      </el-dialog>

      <!-- 遮罩层-显示视频 -->
      <maskLayer
        @click="showMaskLayerSwitches = false"
        :showMaskLayerSwitches="showMaskLayerSwitches"
        :videoURL="videoURL"
      ></maskLayer>
    </div>
  </div>
</template>

<script>
// 富文本编辑器
import { quillEditor } from 'vue-quill-editor'
// ---------------------
import { status } from '@/api/hmmm/constants.js'
import {
  articleListAPI,
  articleRemoveAPI,
  ChangeStateAPI,
  articleAddAPI,
  articleUpdateAPI
} from '@/api/hmmm/articles.js'
import maskLayer from '@/module-hmmm/pages/lxy/maskLayer'
import dayjs from 'dayjs'
export default {
  data() {
    return {
      // 富文本编辑器配置，顶部的工具栏
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['blockquote', 'code-block'], // 引用，代码块
            ['image', 'link']
          ]
        },
        placeholder: '请输入正文'
      },
      tableData: [], // 表格数据
      // ---------
      page: 1, // 当前页数
      pagesize: 5, // 当前页数据量
      total: 0, // 共用多少数据
      keyword: '', // 关键字
      allState: status, // 所有状态
      isState: '', // 选中的状态
      // 新增文章/修改文章对话框---------
      addShowDialog: false, // 对话框开关
      // 对话框内容
      ruleForm: {
        ruleFormTitle: '', // 标题
        ruleFormAddress: null, // 视频地址
        ruleFormText: '' // 文章内容
      },
      // 对话框内容规则
      rules: {
        ruleFormTitle: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        ruleFormAddress: [],
        ruleFormText: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
      },
      dialogTitle: '', // 对话框标题
      userID: '',
      // 预览文章对话框---------
      previewShowDialog: false,
      previewData: {},
      // 显示遮罩层
      showMaskLayerSwitches: false,
      // 视频地址
      videoURL: '',
      // 文章状态
      articleState: null
    }
  },
  components: {
    // 遮罩层组件
    maskLayer,
    // 富文本编辑器
    quillEditor
  },
  created() {
    this.articleList() // 渲染列表
  },
  methods: {
    // 显示遮罩层
    showMaskLayer(videoURL) {
      this.showMaskLayerSwitches = true
      this.videoURL = videoURL
    },
    // 获取文章列表
    async articleList(val) {
      const { data } = await articleListAPI({
        page: this.page, // 当前页数
        pagesize: this.pagesize, // 当前页数据量
        ...val
      })
      this.total = data.counts
      this.tableData = data.items
    },
    // 每页多少条数据
    pageDataAmount(val) {
      this.pagesize = val
      this.articleList()
    },
    // 页数发生改变触发
    goToPage(val) {
      this.page = val
      this.articleList()
    },
    // 处理时间格式
    timeFn(time) {
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    },
    // 处理状态类型
    stateTypeFn(row, column, cellValue, index) {
      const obj = status.find(item => item.value === +cellValue)
      return obj ? '已' + obj.label : '未知'
    },
    // 清除
    clearAllData() {
      this.isState = '' // 清除状态
      this.keyword = '' // 清除关键字
      this.articleList() // 渲染列表
    },
    // 搜索
    searchFind() {
      this.articleList({
        keyword: this.keyword, // 关键字
        state: this.isState // 状态 1 开启 0 屏蔽
      }) // 渲染列表
    },
    // 点击添加文章按钮
    addArticleShowDialog() {
      this.clearAllData()
      this.addShowDialog = true
      this.dialogTitle = '添加文章'
    },
    // 关闭/取消 添加文章
    cancel() {
      this.addShowDialog = false // 对话框开关
      this.$refs.ruleForm.resetFields() // 清空
    },
    // 确认
    Confirmation() {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return
        if (this.dialogTitle === '添加文章') {
          await articleAddAPI({
            title: this.ruleForm.ruleFormTitle, // 标题
            articleBody: this.ruleForm.ruleFormText, // 内容
            videoURL: this.ruleForm.ruleFormAddress // 视频
          })
        }
        if (this.dialogTitle === '修改文章') {
          await articleUpdateAPI({
            id: this.userID,
            title: this.ruleForm.ruleFormTitle, // 标题
            articleBody: this.ruleForm.ruleFormText, // 内容
            videoURL: this.ruleForm.ruleFormAddress // 视频
          })
        }
        this.cancel() // 关闭窗口
        this.$message.success('添加成功')
        this.articleList() // 渲染列表
      })
    },
    // index序号处理
    indexFn(val) {
      return (this.page - 1) * this.pagesize + val + 1
    },
    // 预览
    openPreviewDialog(row) {
      // 打开预览弹窗
      this.previewShowDialog = true
      // 预览弹框内的数据
      this.previewData = row
    },
    // 删除
    deleteArticle(id) {
      console.log(id)
      this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data } = await articleRemoveAPI({ id: id })
          if (data.success) this.$message.success('删除文章成功!')
          this.articleList() // 渲染列表
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    // 状态-启用禁用
    async disable(row) {
      await ChangeStateAPI({
        id: row.id,
        state: (row.state = !row.state ? (this.articleState = 1) : (this.articleState = 0))
      })
    },
    // 修改内容
    updateArticle(row) {
      this.addShowDialog = true
      this.dialogTitle = '修改文章'
      this.userID = row.id
      this.ruleForm = {
        ruleFormTitle: row.title,
        ruleFormText: row.articleBody,
        ruleFormAddress: row.videoURL
      }
    }
  }
}
</script>

<style scoped >
.hmmm_wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 25px;
}
.el-alert {
  margin-bottom: 15px;
}
.el-icon-film {
  color: blue;
  font-size: 20px;
}
.cell {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
}
.title {
  border-bottom: 1px dashed #ccc;
  padding-bottom: 10px;
}
.title span {
  margin-left: 10px;
  margin-top: 10px;
}
.content {
  background: #f5f5f5;
  padding: 10px;
}
.fuwenben {
  height: 235px;
}
</style>
